{% extends "button.html" %}
{% block title %}
    <title>Pooling信息</title>
{% endblock %}


{% block content %}
    <div class="jumbotron">
        <h1>甲基化早筛项目数据库管理系统Demo</h1>
        <h4>Pooling映射表</h4>
    </div>
{% endblock %}

{% block plot %}
    <div class="row">
        <div id="plot_highcharts" style="width: 550px; height: 400px; margin: 0 auto" class="col-9"></div>
        <div id="plot_button" class="form-group col-3">
            <label for="plot_highcharts_field"> 请选择用于画图的关键字段</label>
            <select class="form-control" id="plot_highcharts_field" name="plot_highcharts_field">
                <option value="mass" selected="selected">取样</option>
                <option value="pooling_ratio">pooling比例</option>
                <option value="volume">体积</option>
            </select>
        </div>
    </div><br>
{% endblock %}

{% block table %}
    <!-- datatables -->
    <table id="table_id" class="display">
        <thead>
        <tr>
            <th>索引</th>
            <th>样本编号</th>
            <th>DNA提取编号</th>
            <th>建库编号</th>
            <th>捕获文库名</th>
            <th>测序文库编号</th>
            <th>pooling比例</th>
            <th>取样(ng)</th>
            <th>体积(ul)</th>
            <th>备注</th>
            <th>上次修改时间</th>
            <th>创建时间</th>
            <th>操作</th>
        </tr>
        </thead>
    </table>
{% endblock %}

{% block ModalForm %}
    <div class="form-group">
        <span><a class="text-danger front-weight-bold">* </a>
        <label for="singleLB_id"> 建库编号</label></span>
        <input type="text" class="form-control" id="singleLB_id" name="singleLB_id"
               placeholder="请输入建库编号，必填" required="true">
    </div>
    <div class="form-group">
        <span><a class="text-danger front-weight-bold">* </a>
            <label for="poolingLB_id"> 捕获文库名</label></span>
        <input type="text" class="form-control" id="poolingLB_id" name="poolingLB_id"
               placeholder="请输入捕获文库名，必填" required="true">
    </div>
    <div class="form-group">
        <span><a class="text-danger front-weight-bold">* </a>
            <label for="singleLB_Pooling_id"> 测序文库编号</label></span>
        <input type="text" class="form-control" id="singleLB_Pooling_id" name="singleLB_Pooling_id"
               placeholder="请输入测序文库编号，必填" required="true">
    </div>
    <div class="form-group">
        <label for="pooling_ratio"> pooling比例</label>
        <input type="number" step="0.01" class="form-control" id="pooling_ratio" name="pooling_ratio"
               placeholder="请输入pooling比例，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="mass"> 取样(ng)</label>
        <input type="number" step="0.01" class="form-control" id="mass" name="mass"
               placeholder="请输入取样(ng)，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="volume"> 体积(ul)</label>
        <input type="number" step="0.01" class="form-control" id="volume" name="volume"
               placeholder="请输入体积(ul)，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="others"> 备注</label>
        <input type="text" class="form-control" id="others" name="others"
               placeholder="请输入备注，默认：无" value="无">
    </div>
{% endblock %}

{% block extra_js %}
    <script>
        $(document).ready(function () {
            let url = '/api/PoolingInfo/';
            let url2 = '/api/LibraryInfo/';
            let url3 = '/api/CaptureInfo/';
            let dataModelForm;
            let fieldForPie = $('#plot_highcharts_field');

            function MyModelInit(title_name, data) {
                dataModelForm = data;
                if (title_name === '更新') {
                    $('#sample_id').val(data['sample_id']);
                    $('#dna_id').val(data['dna_id']);
                    $('#singleLB_id').val(data['singleLB_id']);
                    $('#poolingLB_id').val(data['poolingLB_id']);
                    $('#pooling_ratio').val(data['pooling_ratio']);
                    $('#mass').val(data['mass']);
                    $('#volume').val(data['volume']);
                    $('#singleLB_Pooling_id').val(data['singleLB_Pooling_id']);
                    $('#others').val(data['others']);
                    $('#type').val('edit');
                    $('#modal_title').text('更新');
                } else {
                    $('#singleLB_id').val("");
                    $('#poolingLB_id').val("");
                    $('#pooling_ratio').val("");
                    $('#mass').val("");
                    $('#volume').val("");
                    $('#singleLB_Pooling_id').val("");
                    $('#others').val("");
                    $('#type').val('new');
                    $('#modal_title').text('新增');
                }
            }

            let table = $('#table_id').DataTable({
                "language": {
                    "lengthMenu": "选择每页 _MENU_ 展示 ",
                    "zeroRecords": "未找到匹配结果--抱歉",
                    "info": "当前显示第 _PAGE_ 页结果，共 _PAGES_ 页",
                    "infoEmpty": "没有数据",
                    "search": "搜索",
                    "infoFiltered": "(获取 _MAX_ 项结果)",
                    "paginate": {
                        "first": "首页",
                        "previous": "上一页",
                        "next": "下一页",
                        "last": "末页"
                    }
                },
                "scrollY": "5000px",
                "scrollCollapse": true,
                "scrollX": true,
                "pagingType": "full_numbers",
                fixedColumns: true,
                rowReorder: true,
                colReorder: true,
                searching: true,
                select: true,
                dom: 'lB<"clear">frtip',
                buttons: [
                    {
                        extend: 'colvisGroup',
                        text: '显示前5列',
                        show: [0, 1, 2, 3, 4, 5, 12],
                        hide: [6, 7, 8, 9, 10, 11]
                    },
                    {
                        extend: 'colvisGroup',
                        text: '显示全部列',
                        show: ':hidden',
                    },
                    {
                        text: '指定显示列', extend: 'colvis',
                        postfixButtons: ['colvisRestore'],
                        columnText: function (dt, idx, title) {
                            return (idx + 1) + ': ' + title;
                        }
                    },
                    {
                        extend: 'selectAll',
                        text: '全选'
                    }, {
                        extend: 'selectRows',
                        text: '选择多行'
                    }, {
                        extend: 'selectColumns',
                        text: '选择多列'
                    }, {
                        extend: 'selectCells',
                        text: '选择多个单元格'
                    }, {
                        extend: 'selectNone',
                        text: '取消当前选择'
                    },
                    {
                        extend: 'copy',
                        text: '复制到剪切板'
                    }, {
                        extend: 'csv',
                        text: '输出到csv'
                    }
                ],
                "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "全部"]],
                "serverSide": true,
                "processing": true,
                "ajax": "/api/PoolingInfo/?format=datatables",
                "columns": [
                    {
                        data: 'index',
                        width: "1%",
                        // 若想前端显示的不一样，则需要"render"函数
                        'render': function (data, type, full, meta) {
                            return meta.row + 1 + meta.settings._iDisplayStart;
                        }
                    },
                    {"data": "sample_id"},
                    {"data": "dna_id"},
                    {"data": "singleLB_id"},
                    {"data": "poolingLB_id"},
                    {"data": "singleLB_Pooling_id"},
                    {"data": "pooling_ratio"},
                    {"data": "mass"},
                    {"data": "volume"},
                    {"data": "others"},
                    {"data": "last_modify_date"},
                    {"data": "created"},
                    {
                        "data": null,
                        "defaultContent": '<button type="button" class="btn btn-info">更新</button>' + '&nbsp;&nbsp' +
                            '<button type="button" class="btn btn-danger">删除</button>'
                    }
                ]
            });
            table.button(0).trigger();

            let id = 0;
            $('#table_id tbody').on('click', 'button', function () {
                let data = table.row($(this).parents('tr')).data();
                let class_name = $(this).attr('class');
                id = data['index'];
                //alert(id);
                if (class_name === 'btn btn-info') {
                    // EDIT button
                    MyModelInit('更新', data);
                    $("#myModal").modal();
                } else {
                    // DELETE button
                    //alert('delete '+id);
                    //$('#modal_title').text('DELETE');
                    $("#confirm").modal();
                }

            });

            $('#modelForm').on('submit', function (e) {
                e.preventDefault();


                // 递交前检查，一般是检测model的外键是否存在
                let data0 = $.ajax({
                    url: url2, dataType: 'json', contentType: "application/json",
                    type: "get", async: false, data: {singleLB_id: $('#singleLB_id').val()}
                }).responseJSON[0];
                let data1 = $.ajax({
                    url: url3, dataType: 'json', contentType: "application/json",
                    type: "get", async: false, data: {poolingLB_id: $('#poolingLB_id').val()}
                }).responseJSON[0];
                if (data0 === undefined) {
                    $('#myModalError').text('错误！！！建库编号不存在，请填写正确的建库编号。');
                    return
                } else if (data1 === undefined) {
                    $('#myModalError').text('错误！！！捕获文库名不存在，请填写正确的捕获文库名。');
                    return
                }

                let type = $('#type').val();
                let method = '';
                let url_ajax = url;
                if (type === 'new') {
                    // new
                    method = 'POST';
                    // POST前检查，一般是检测model的关键字段值是否存在
                    let data2 = $.ajax({
                        url: url, dataType: 'json', contentType: "application/json",
                        type: "get", async: false, data: {singleLB_Pooling_id: $('#singleLB_Pooling_id').val()}
                    }).responseJSON[0];
                    if (data2 !== undefined) {
                        $('#myModalError').text('错误！！！测序文库编号已存在，无法添加。如需更新该条目，请在对应行进行更新操作。');
                        return
                    }
                } else {
                    // edit
                    url_ajax = url + id + '/';
                    method = 'PUT';
                }


                $.ajax({
                    url: url_ajax,
                    method: method,
                    data: $(this).serialize() + '&' + $.param({
                        sample_id: data0.sample_id,
                        dna_id: data0.dna_id
                    }),
                    headers: {'X-HTTP-Method-Override': 'PATCH'},
                    success: function () {
                        if (type === 'new') {
                            $('#myModalError').text('添加成功！！！测序文库编号：' + $('#singleLB_Pooling_id').val());
                        } else {
                            $('#myModalError').text('更新成功！！！测序文库编号：' + $('#singleLB_Pooling_id').val());
                        }

                        setTimeout(
                            function () {
                                location.reload();
                            }, 3000
                        );
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $('#myModalError').text('出现错误！！！请联系管理员');
                        console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                    }
                });

            });

            $('#confirm').on('click', '#delete', function (e) {
                $.ajax({
                    url: url + id + '/',
                    method: 'DELETE',
                    success: function () {
                        location.reload()
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                    }
                });
            });


            $('#new').on('click', function (e) {
                MyModelInit('新增', {});
                $("#myModal").modal();
            });

            // pooling号下拉选框
            //$('#poolingLB_id').focus(function () {
            //    let poolingLB_ids = $.ajax({
            //        url: '/api/CaptureInfo/', dataType: 'json', contentType: "application/json",
            //        type: "get", async: false
            //    }).responseJSON.results;
            //    $.each(poolingLB_ids, function (index, value) {
            //        $('#poolingLB_id').append('<option value="' + value.poolingLB_id + '">' + value.poolingLB_id + '</option>')
            //    });
            //});

            $('#upload').on('click', function (e) {
                $('#uploadOperator').val("");
                $('#uploadFile').val("");
                $('#uploadError').val("");
                $('#uploadUrl').val('PoolingInfo');
                $("#uploadModal").modal();
            });

            $('#bulkDel').on('click', function (e) {
                $('#bulkDelUrl').val('PoolingInfo');
                $("#bulkDelModal").modal();
            });

            $('.downloadExcel').on('click', function (e) {
                e.preventDefault();
                window.location.href = '/download_excel/PoolingInfo/'
            });

            $('#myModalReset').on('click', function (e) {
                e.preventDefault();
                if ($('#modal_title').text() === '更新') {
                    MyModelInit('更新', dataModelForm);
                } else {
                    MyModelInit('新增', {});
                }
            });

            pie_plot('PoolingInfo', fieldForPie.val(), fieldForPie.find("option:selected").text());

            fieldForPie.change(function () {
                pie_plot('PoolingInfo', fieldForPie.val(), fieldForPie.find("option:selected").text());
            });
        })

    </script>
{% endblock %}